In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
#importing some useful packages
import matplotlib.pyplot as plt
#import matplotlib.image as mpimg
import numpy as np
import pandas as pd
#import cv2
%matplotlib inline
IMG_HEIGHT = 32
IMG_WIDTH = 32
from pathlib import Path
import sys
import os
!mkdir car
proj_folder = Path("/content/car")
os.chdir(proj_folder)
!git clone https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project
proj_folder = Path("/content/car/CarND-Traffic-Sign-Classifier-Project/")
os.chdir(proj_folder)
data_dir = "data"
!mkdir {data_dir}
os.chdir(data_dir)
!wget https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/traffic-signs-data.zip
!unzip -o traffic-signs-data.zip
!ls
# Load pickled data
import pickle
training_file = 'train.p'
validation_file = 'valid.p'
testing_file = 'test.p'
#os.path.join(proj_folder, data_dir, validation_file)
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
#with open(file2write, 'wb') as config_dictionary_file:
# pickle.dump(dictionary, config_dictionary_file)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
s_train, c_train = train['sizes'], train['coords']
s_valid, c_valid = valid['sizes'], valid['coords']
s_test, c_test = test['sizes'], test['coords']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
print(f"X_train {X_train.shape}, y_train {y_train.shape}")
print(f"X_valid {X_valid.shape}, y_valid {y_valid.shape}")
print(f"X_test {X_test.shape}, y_test {y_test.shape}")
# print(f"y_train classes/counts {np.unique(y_train).shape}:{np.unique(y_train, return_counts=True)}")
# print(f"y_valid classes/counts {np.unique(y_valid).shape}:{np.unique(y_valid , return_counts=True)}")
# print(f"y_test classes/counts {np.unique(y_test).shape}:{np.unique(y_test , return_counts=True)}")
print('Train Labels')
display(pd.DataFrame({'qty':np.unique(y_train, return_counts=True)[1]}).T)
print('\nValidation Labels')
display(pd.DataFrame({'qty':np.unique(y_valid, return_counts=True)[1]}).T)
print('\nTest Labels')
display(pd.DataFrame({'qty':np.unique(y_test, return_counts=True)[1]}).T)
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = 34799
# TODO: Number of validation examples
n_validation = 4410
# TODO: Number of testing examples.
n_test = 12630
# TODO: What's the shape of an traffic sign image?
image_shape = (32, 32)
# TODO: How many unique classes/labels there are in the dataset.
n_classes = 43
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
names = pd.read_csv(os.path.join(proj_folder,'signnames.csv'), index_col='ClassId')
display(names)
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
#import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
#%matplotlib inline
rows = 10
cols = 10
offset = 600
plt.figure(figsize=(20,20))
for i, img in enumerate(X_valid[offset:offset+100]):
plt.subplot(rows, cols, i+1, title=names.iloc[y_valid[i+offset]].SignName), plt.imshow(img, aspect='auto')
def mask_image(img, coords, sizes):
x1, y1, x2, y2 = coords
w, h = sizes
img[:int(x1*IMG_WIDTH/w)] = 0
img[int(x2*IMG_WIDTH/w):] = 0
img[:,:int(y1*IMG_HEIGHT/h)] = 0
img[:,int(y2*IMG_HEIGHT/h):] = 0
return img
#plt.imshow(img, aspect='auto')
def mask_dataset(data, coord_data, size_data):
for i, img in enumerate(data):
mask_image(img, coord_data[i], size_data[i])
mask_dataset(X_train, c_train, s_train)
mask_dataset(X_valid, c_valid, s_valid)
mask_dataset(X_test, c_test, s_test)
#'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
#'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE
rows = 10
cols = 10
offset = 600
plt.figure(figsize=(20,20))
for i, img in enumerate(X_valid[offset:offset+100]):
plt.subplot(rows, cols, i+1, title=names.iloc[y_valid[i+offset]].SignName), plt.imshow(img, aspect='auto')
signs_ref = pd.DataFrame({'Pict':list(X_test)})
signs_ref['lab'] = y_test #np.argmax(y_test, axis=1)
print(signs_ref.shape)
print(np.array(list(signs_ref.groupby(by='lab').first().Pict)).shape)
rows = 5
cols = 10
#offset = 300
plt.figure(figsize=(20,12))
for i, img in enumerate(np.array(list(signs_ref.groupby(by='lab').nth(5).Pict))):
ax = plt.subplot(rows, cols, i+1) #, title=names.iloc[i].SignName)
ax.set_title(names.iloc[i].SignName, wrap=True)
plt.imshow(img, aspect='auto')
#plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D, Input, \
GlobalAveragePooling2D, BatchNormalization, Activation
from tensorflow.keras.models import load_model, model_from_json
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#!pip install tensorflow-addons
import tensorflow_addons as tfa
batch_size = 128
epochs = 75
y_train = to_categorical(y_train, n_classes)
y_valid = to_categorical(y_valid , n_classes)
y_test = to_categorical(y_test , n_classes)
print(f"X_train {X_train.shape}, y_train {y_train.shape}")
print(f"X_valid {X_valid.shape}, y_valid {y_valid.shape}")
print(f"X_test {X_test.shape}, y_test {y_test.shape}")
data_gen_args = dict(#samplewise_center=True,
samplewise_std_normalization=True,
rotation_range=50,
#zca_whitening=True,
#zca_epsilon=1e-06,
zoom_range=0.2,
rescale=1./255,
width_shift_range=0.2,
height_shift_range=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)
valid_datagen = ImageDataGenerator(**data_gen_args)
# Provide the same seed and keyword arguments to the fit and flow methods
seed = 1
# Only required if featurewise_center or featurewise_std_normalization or zca_whitening are set to True.
#image_datagen.fit(X_train, augment=True, seed=seed)
#valid_datagen.fit(X_valid, augment=True, seed=seed)
data_gen_args2 = dict(#samplewise_center=True,
samplewise_std_normalization=True,
rescale=1./255)
test_datagen = ImageDataGenerator(**data_gen_args2)
# Only required if featurewise_center or featurewise_std_normalization or zca_whitening are set to True.
#test_datagen.fit(X_test, augment=True, seed=seed)
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import json
import requests
def to_telegram(mess, cmd=None):
bot_id = "867533512:AAGgw33CTqg4QAXy4XyRbC....."
chat_id="123456789"
if cmd is None:
address="https://api.telegram.org/bot" + bot_id + "/sendMessage"
data = {'chat_id': chat_id, 'text': mess}
else:
address="https://api.telegram.org/bot" + bot_id + cmd
data = {'chat_id': chat_id}
print('cmd:{}'.format(cmd))
try:
r = requests.post(address, data=data)
print("telegram API result:", r)
except (HTTPSConnectionPool, TimeoutError) as err:
if '200' in err:
print("telegram API result: {}".format(err))
else:
print('to_telegram failed: {}'.format(err))
else:
print('to_telegram failed.')
class YourTelegramCallback(tf.keras.callbacks.Callback):
def on_train_batch_end(self, batch, logs=None):
pass
#print('For batch {}, loss is {:7.2f}.'.format(batch, logs['loss']))
def on_test_batch_end(self, batch, logs=None):
pass
#print('For batch {}, loss is {:7.2f}.'.format(batch, logs['loss']))
def on_epoch_end(self, epoch, logs=None):
#print('The average loss for epoch {} is {:7.2f} and mean absolute error is {:7.2f}.'.format(epoch, logs['loss'], logs['mae']))
#to_telegram('Epoch {}, val_loss {:7.3f}, val_dice_coef {:7.3f}.'.format(epoch, logs['val_loss'], logs['val_dice_coef']))
to_telegram('Epoch {}, val_loss {:7.3f}, val_acc {:7.3f}.'.format(epoch, logs['val_loss'], logs['val_accuracy']))
def plot_history(history, title, ix_number=-1, y_true=None, bins=50, accuracy=[]):
# plot train and validation loss
# history - dictionary
# loss, val_loss - keys for the plot
# accuracy=['accuracy', 'val_accuracy'] - keys for the accuracy plot
# ix_number - list index of the list values in history['pred'][ix_number] or the last one default
# pred - key and values list must match y_true length for the histogram
# bins - bins quantity for the hystogram
fig = plt.figure(figsize=(14,5))
ax = fig.add_subplot(1, 2, 1)
ax.set_title(title)
ax.plot(history['loss'], label='Model loss')
ax.plot(history['val_loss'], label='Model val_loss')
ax.set_ylabel('loss')
ax.set_xlabel('epoch')
if len(accuracy)==0:
ax.legend(loc='upper right') #['train','validation'], loc='upper right')
elif len(accuracy)==2:
ax2 = ax.twinx()
ax2.plot(history[accuracy[0]], label='Train')
ax2.plot(history[accuracy[1]], label='Validation')
ax2.set_ylabel('accuracy')
ax2.legend(loc='right')
ax = fig.add_subplot(1, 2, 2)
ax.set_title(title)
if 'pred' in history.keys():
if ix_number==-1:
ix = len(history['pred'])-1
else:
ix = ix_number
if y_true is None:
ax.hist(history['pred'][ix], label='prediction', bins=bins)
else:
#ax.hist([history['pred'][ix], y_true], label=['prediction', 'y_true'], bins=bins)
ax.hist(np.concatenate((history['pred'][ix], y_true), axis=1),
label=['prediction', 'y_true'],
color=['red', 'lime'],
bins=bins)
ax.legend(prop={'size': 10})
ax.set_xlabel('target')
print('predictions ', len(history['pred']))
fig.tight_layout()
plt.show()
# https://www.kaggle.com/artgor/where-do-the-robots-drive
from sklearn.metrics import confusion_matrix #mean_squared_error, accuracy_score
import itertools
def plot_confusion_matrix(truth, pred, classes, normalize=False, title='', to_file=None, figsize=(10, 10)):
cm = confusion_matrix(truth, pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig = plt.figure(figsize=figsize)
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('Confusion matrix', size=15)
plt.colorbar(fraction=0.046, pad=0.04)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.grid(False)
plt.tight_layout()
if to_file is None:
plt.show()
else:
plt.savefig(to_file, bbox_inches='tight')
plt.close(fig)
def save_model_n(data_folder, model, history_dict, mod_number):
# serialize model to JSON
model_json = model.to_json()
file_to_save = data_folder / ("model" + str(mod_number) + ".json")
with open(file_to_save, "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
with open(file_to_save, "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
file_to_save = str(data_folder / ("model" + str(mod_number) + ".h5"))
print('file_to_save:', file_to_save)
model.save_weights(file_to_save)
print("Saved model to disk")
file_to_save = data_folder / ("history_" + str(mod_number) + ".pickle")
with open(file_to_save, 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(history_dict, f, pickle.HIGHEST_PROTOCOL)
def load_model_n(data_folder, mod_number):
# load json and create model
file_to_read = data_folder / ("model" + str(mod_number) + ".json")
json_file = open(file_to_read, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
file_to_read = data_folder / ("model" + str(mod_number) + ".h5")
loaded_model.load_weights(str(file_to_read))
print("Loaded model from disk")
# evaluate loaded model on test data
loaded_model.compile(loss='mse', optimizer='adam') #, metrics=['accuracy'])
file_to_read = data_folder / ("history_" + str(mod_number) + ".pickle")
with open(file_to_read, 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
history_ = pickle.load(f)
return loaded_model, history_
callback = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=10, restore_best_weights=True)
#ResNet50(include_top=True, weights='imagenet', input_tensor=None, input_shape=None,
# pooling=None, classes=1000, **kwargs)
def create_resnet_model(drop_rate=0.1, rnet_out_name="conv3_block3_out",
optimizer = tf.keras.optimizers.Adam(), loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)):
base_model = tf.keras.applications.ResNet50(weights= 'imagenet', include_top=False, input_shape= (IMG_HEIGHT, IMG_WIDTH,3))
#x = base_model.output
#x = base_model.get_layer("conv4_block6_out").output
x = base_model.get_layer(rnet_out_name).output
#x = GlobalAveragePooling2D()(x)
x = Flatten()(x)
x = Dense(2048, activation='relu', name='dense_1')(x)
x = Dropout(drop_rate, name='drop_1')(x)
x = Dense(512, activation='relu', name='dense_2')(x)
x = Dropout(drop_rate, name='drop_2')(x)
#outputs = Dense(n_classes, name='predictions', activation= 'softmax')(x)
outputs = Dense(n_classes, name='predictions')(x)
model_r = tf.keras.Model(inputs=base_model.input, outputs=outputs)
#loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True) # used with one hot labels
#loss_object = tf.keras.losses.SparseCategoricalCrossentropy( ) # used with integer labels
#test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
model_r.compile(optimizer=optimizer,
loss=loss_object,
metrics=['accuracy'])
return model_r
radam = tfa.optimizers.RectifiedAdam()
ranger = tfa.optimizers.Lookahead(radam, sync_period=10, slow_step_size=0.5)
model_r = create_resnet_model(drop_rate=0.2, rnet_out_name="conv2_block3_out", optimizer = ranger)
model_r.summary()
#tf.keras.utils.plot_model(model_r, show_shapes=True, dpi=64) #dilation_rate
def create_2kernel_cnn(drop_rate=0.2):
padding='same'
inputs = Input(shape=(IMG_HEIGHT, IMG_WIDTH ,3), name='input')
x = Conv2D(16, 5, padding=padding, activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3))(inputs)
y = Conv2D(16, 3, padding=padding, activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3))(inputs)
x = MaxPooling2D()(x)
y = MaxPooling2D()(y)
x = Conv2D(32, 5, padding=padding, activation='relu')(x)
y = Conv2D(32, 3, padding=padding, activation='relu')(y)
x = MaxPooling2D()(x)
y = MaxPooling2D()(y)
x = Conv2D(64, 5, padding=padding, activation='relu')(x)
y = Conv2D(64, 3, padding=padding, activation='relu')(y)
x = MaxPooling2D()(x)
y = MaxPooling2D()(y)
x = Conv2D(128, 5, padding=padding, activation='relu')(x)
y = Conv2D(128, 3, padding=padding, activation='relu')(y)
x = tf.keras.layers.concatenate([x, y])
x = Flatten()(x)
x = Dense(2048, activation='relu', name='dense_1')(x)
x = Dropout(drop_rate, name='drop_1')(x)
x = Dense(512, activation='relu', name='dense_2')(x)
x = Dropout(drop_rate, name='drop_2')(x)
outputs = Dense(n_classes, name='predictions')(x)
model_f = tf.keras.Model(inputs=inputs, outputs=outputs)
loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
optimizer = tf.keras.optimizers.Adam()
#test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
model_f.compile(optimizer=optimizer,
loss=loss_object,
metrics=['accuracy'])
return model_f
#model_r = create_2kernel_cnn()
#model_r.summary()
#tf.keras.utils.plot_model(model_r, show_shapes=True, dpi=64)
def create_conv_net(net_type='lenet5', padding='valid', drop_rate=0.2, activation='relu', dense_layers=[4096,512], batch_norm=False,
optimizer = 'adam',
loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)):
inputs = Input(shape=(IMG_HEIGHT, IMG_WIDTH ,3), name='input')
x = Conv2D(32, 5, padding=padding, input_shape=(IMG_HEIGHT, IMG_WIDTH ,3), name='conv_1')(inputs)
if net_type=='lenet5':
x = Activation(activation)(x)
x = MaxPooling2D()(x)
else:
if batch_norm:
x = BatchNormalization()(x)
x = Activation(activation)(x)
x = Conv2D(64, 5, padding=padding, name='conv_2')(x)
x = Activation(activation)(x)
if net_type=='lenet5':
x = MaxPooling2D()(x)
x = Conv2D(128, 5, padding=padding, name='conv_3')(x)
x = Activation(activation)(x)
if net_type=='lenet5':
x = MaxPooling2D()(x)
x = Conv2D(128, 5, padding=padding, name='conv_4')(x)
x = Activation(activation)(x)
if net_type=='lenet5':
x = MaxPooling2D()(x)
x = Flatten()(x)
x = Dense(dense_layers[0], activation='relu', name='dense_1')(x)
x = Dropout(drop_rate, name='drop_1')(x)
x = Dense(dense_layers[1], activation='relu', name='dense_2')(x)
x = Dropout(drop_rate, name='drop_2')(x)
outputs = Dense(n_classes, name='predictions')(x)
model_f = tf.keras.Model(inputs=inputs, outputs=outputs)
#loss_object = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
#optimizer = tf.keras.optimizers.Adam()
#test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
model_f.compile(optimizer=optimizer,
loss=loss_object,
metrics=['accuracy'])
return model_f
radam = tfa.optimizers.RectifiedAdam()
ranger = tfa.optimizers.Lookahead(radam, sync_period=6, slow_step_size=0.5)
model_r = create_conv_net(net_type='convnet', drop_rate=0.25, padding='valid', batch_norm=True, dense_layers=[4096,512], optimizer = ranger)
model_r.summary()
tf.keras.utils.plot_model(model_r, show_shapes=True, dpi=64)
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
history_dict = {}
history = model_r.fit(
image_datagen.flow(X_train, y=y_train, batch_size=batch_size),
steps_per_epoch=len(X_train) // batch_size,
epochs=epochs,
validation_data=valid_datagen.flow(X_valid, y_valid, batch_size=batch_size),
callbacks=[callback, YourTelegramCallback()])
history_dict = history.history.copy()
save_model_n(proj_folder, model_r, history_dict, 1)
test_loss, test_acc = model_r.evaluate(test_datagen.flow(X_test, y_test), verbose=2)
print('\nTest accuracy:', test_acc)
to_telegram(f'test_datagen loss:{test_loss:<8.3f}, acc:{test_acc:<8.3f}')
y_hat = model_r.predict(test_datagen.flow(X_test, shuffle=False), verbose=2)
y_hat = np.argmax(y_hat, axis=1)
history_dict['pred'] = []
history_dict['pred'].append(y_hat[...,np.newaxis])
plot_history(history_dict,'train', y_true=np.argmax(y_test, axis=1)[...,np.newaxis],accuracy=['accuracy', 'val_accuracy'], bins=43)
plot_confusion_matrix(np.argmax(y_test, axis=1), y_hat, names.SignName, normalize=False, title='', to_file=None, figsize=(20,20))
#395/395 - 11s - loss: 0.3276 - accuracy: 0.9325 resnet drop_rate=0.2, rnet_out_name="conv3_block4_out"
#395/395 - 11s - loss: 0.3835 - accuracy: 0.9162 resnet drop_rate=0.2, rnet_out_name="conv3_block3_out"
#395/395 - 11s - loss: 0.3994 - accuracy: 0.9241 resnet drop_rate=0.5, rnet_out_name="conv3_block3_out"
#395/395 - 11s - loss: 0.4806 - accuracy: 0.9030 resnet drop_rate=0.5, rnet_out_name="conv2_block3_out"
#395/395 - 10s - loss: 0.3058 - accuracy: 0.9285 lenet-5 masked input
#395/395 - 10s - loss: 0.3954 - accuracy: 0.9013 lenet-5 not masked input
#395/395 - 7s - loss: 0.3612 - accuracy: 0.9113 lenet-5 masked input augment 0.3
#395/395 - 7s - loss: 0.4979 - accuracy: 0.8884 lenet-5 masked input augment 0.3 early acc
#395/395 - 2s - loss: 0.5252 - accuracy: 0.8732 lenet-5 masked input, augment 0.3, early loss, padding valid
#395/395 - 2s - loss: 0.5594 - accuracy: 0.8599 lenet-5 masked input, augment 0.3, early loss, padding same
#395/395 - 2s - loss: 0.5413 - accuracy: 0.8790 lenet-5 masked input augment 0.3 early acc, padding valid, scale 1/128
#395/395 - 24s - loss: 5.1071 - accuracy: 0.2344 lenet-5 masked input augment 0.3 early acc, padding valid, scale 1/128, ZCA-withening
#395/395 - 2s - loss: 0.5465 - accuracy: 0.8960 lenet-5 masked input, shift 0.2, Std, No Mean, early acc, padding valid, scale 1/255
#395/395 - 2s - loss: 0.5514 - accuracy: 0.8961 lenet-5 masked input, shift 0.2, Std, No Mean, early acc, padding valid, scale 1/255, batch 128
#395/395 - 2s - loss: 0.4610 - accuracy: 0.9088 lenet-5 - no maxpool, masked input, shift 0.2, Std, No Mean, early acc, padding valid, scale 1/255, batch 128
#395/395 - 2s - loss: 0.2701 - accuracy: 0.9372 lenet-5 - no maxpool, 16x32
#395/395 - 2s - loss: 0.2052 - accuracy: 0.9565 lenet-5 - no maxpool, 16x32x64
#395/395 - 3s - loss: 0.2410 - accuracy: 0.9602 lenet-5 - no maxpool, 16x32x64x128
#395/395 - 2s - loss: 0.1581 - accuracy: 0.9687 32x64x128x4048x512 lookahead(10)
#395/395 - 3s - loss: 0.1927 - accuracy: 0.9562 32x64x128x128x4048x512 lookahead(10)
#395/395 - 3s - loss: 0.1924 - accuracy: 0.9543 32x64x128x128x2048x512 lookahead(10) BatchNorm, no maxpool
#395/395 - 2s - loss: 0.3316 - accuracy: 0.9269 drop_rate=0.2, rnet_out_name="conv2_block3_out" lookahead(10)
#395/395 - 3s - loss: 0.1885 - accuracy: 0.9661 16x32x64x128x2048x512 Adam BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 4s - loss: 0.2483 - accuracy: 0.9576 16x32x64x128x4096x512 Adam BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 2s - loss: 0.1951 - accuracy: 0.9536 16x32x64x128x1500x512 Adam BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 2s - loss: 0.2471 - accuracy: 0.9491 16x32x64x128x1024x512 Adam BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 3s - loss: 0.3386 - accuracy: 0.9468 16x32x64x128x2048x512 Adam BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 3s - loss: 0.2952 - accuracy: 0.9430 16x32x64x128x2048x512 Adam no BatchNorm, no maxpool, drop_rate=0.2
#395/395 - 2s - loss: 0.2875 - accuracy: 0.9553 32x64x128x128x4096x512 Adam BatchNorm, no maxpool, drop_rate=0.25
#395/395 - 2s - loss: 0.2502 - accuracy: 0.9475 128x64x32x32x4096x512 Adam BatchNorm, no maxpool, drop_rate=0.25
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
os.path.join(proj_folder, data_dir, 'schield*.jpg')
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
#import matplotlib.image as mpimg
import cv2
import glob
from math import ceil
#pict1 = 'schield1.jpg'
images = glob.glob(os.path.join(proj_folder, data_dir, 'schield*.jpg'))
#rows = ceil(len(images)/2.0)
cols = len(images)
plt.figure(figsize=(18,3))
for i, fname in enumerate(sorted(images)):
img = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2RGB)
plt.subplot(1, cols, i+1, title=os.path.basename(fname)), plt.imshow(img, aspect='auto')
plt.show()
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
X_new = []
for i, fname in enumerate(sorted(images)):
img = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2RGB)
X_new.append(img)
X_new = np.array(X_new)
X_new.shape
#model_r = load_model(os.path.join(proj_folder, model_file))
model, hist = load_model_n(proj_folder, 1)
model.summary()
y_hat = model.predict(test_datagen.flow(X_new, shuffle=False), verbose=2)
y_cat = np.argmax(y_hat, axis=1)
y_cat
names.iloc[y_cat].SignName.tolist()
plt.figure(figsize=(20,3))
for i, fname in enumerate(sorted(images)):
img = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2RGB)
plt.subplot(1, cols, i+1, title=names.iloc[y_cat].SignName.tolist()[i]), plt.imshow(img, aspect='auto')
plt.show()
rows = 5
cols = 10
#offset = 300
plt.figure(figsize=(20,12))
for i, img in enumerate(np.array(list(signs_ref.groupby(by='lab').nth(5).Pict))):
ax = plt.subplot(rows, cols, i+1) #, title=names.iloc[i].SignName)
ax.set_title(names.iloc[i].SignName, wrap=True)
plt.imshow(img, aspect='auto')
#plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print(f'Two signs are not in dataset\nThe accuracy for the 5 images in dataset is {4/5*100}%')
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
logits, idxs = tf.math.top_k(tf.constant(y_hat), k=5)
#[ 0, 11, 28, 5, 1]
for i, indices in enumerate(idxs):
print(np.array(logits[i]))
print(names.iloc[indices].SignName.tolist(), '\n')
see project3.md on github